package com.gomyb.redis.serializer;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

/**
 * @author <a href="mailto:hellohesir@gmail.com">Mr_He</a>
 * 2019/9/12 13:51
 * 对象转换
 */
public class RedisObjectSerializer implements RedisSerializer<Object> {

    // 定义序列化与反序列化转换器
    private Converter<Object, byte[]> serializingConverter = new SerializingConverter();

    private Converter<byte[], Object> deserializingConverter = new DeserializingConverter();

    private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; // 做一个空数组，不是null

    @Override
    public byte[] serialize(Object obj) throws SerializationException {
        if (null == obj) {
            return EMPTY_BYTE_ARRAY;
        }
        return this.serializingConverter.convert(obj); // 将对象变为字节数组
    }

    @Override
    public Object deserialize(byte[] data) throws SerializationException {
        if (data == null || data.length == 0) { // 此时没有对象的内容信息
            return null;
        }
        return this.deserializingConverter.convert(data);
    }

}
